<template>
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :http-request="upload"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { postUpload } from '@/api/management/user'
export default {
  name: 'Eupload',
  props: {
    // 图片路径
    url: {
      type: String,
      default: ''
    }
  },
  watch: {},
  data () {
    return {
      imageUrl: '',
      baseUrl: ''
    }
  },
  async created () {
    this.showImg()
  },
  watch: {
    url: {
      handler () {
        this.showImg()
      }
    }
  },
  methods: {
    // 显示的图片
    showImg () {
      this.baseUrl = this.$store.getters.baseUrl
      if (this.url.includes(this.baseUrl)) {
        this.imageUrl = this.url
      } else if (this.url) {
        this.imageUrl = this.baseUrl + this.url
      } else {
        this.imageUrl = ''
      }
    },
    // 上传前
    beforeAvatarUpload (file) {},
    async upload (file) {
      let FD = new FormData()
      FD.append(`file`, file.file)
      let data = await postUpload(FD)
      if (data.code == 0 && data.data.bcode == 0) {
        this.imageUrl = this.baseUrl + data.data.bdata[1]
        // 把上传成功的地址后缀传递出去
        this.$emit('uploadImg', data.data.bdata[1])
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload {
  display: flex;
  align-items: center;
  justify-content: center;
  ::v-deep {
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
